package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDTO;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    BehaviorFeign behaviorFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 标记当前方法会被线程池异步执行
     *
     * @param dto
     */
    @Async("taskExecutor")//线程池Bean的名称
    @Override
    public void insert(UserSearchDTO dto) {
        log.info("异步记录搜索历史记录 开始.....................");
        //1.根据当前登录用户id或者设备id远程查询行为实体数据
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(dto.getUserId(), dto.getEquipmentId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用行为微服务失败");
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        //2.根据行为entryId和keywork查询这个历史记录是否已经保存
        ApUserSearch userSearch = mongoTemplate.findOne(Query.query(Criteria
                        .where("entryId").is(behaviorEntry.getId())
                        .and("keyword").is(dto.getSearchWords())),
                ApUserSearch.class);
        if (userSearch != null) {
            //3.如果已经有这个历史记录，执行修改时间
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
        } else {
            //4.如果没有这个历史记录，创建并保存
            userSearch = new ApUserSearch();
            userSearch.setEntryId(behaviorEntry.getId());
            userSearch.setKeyword(dto.getSearchWords());
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
        }
        log.info("异步记录搜索历史记录 结束.....................");
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDTO dto) {
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorEntryResult = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if(!behaviorEntryResult.checkCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用行为服务失败");
        }
        ApBehaviorEntry behaviorEntry = behaviorEntryResult.getData();
        if(behaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
        }
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(dto.getId()).and("entryId").is(behaviorEntry.getId())),ApUserSearch.class);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        Integer size = 10;
        ApUser user = AppThreadLocalUtils.getUser();
        //1.根据当前登录用户id或者设备id远程查询行为实体数据
        ResponseResult<ApBehaviorEntry> result = behaviorFeign.findByUserIdOrEquipmentId(user==null?null:user.getId(), dto.getEquipmentId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用行为微服务失败");
        }
        ApBehaviorEntry behaviorEntry = result.getData();
        //2.根据行为实体id  时间降序排序 默认查询前10条记录
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria
                                .where("entryId").is(behaviorEntry.getId()))
                        .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                        .limit(size),
                ApUserSearch.class);
        //3.返回历史记录列表

        return ResponseResult.okResult(apUserSearches);
    }
}
